<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    :title="getTitle"
    width="35%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup name="CategoryModal">
import { ref, computed, unref } from "vue";
import { BasicForm, useForm } from "/@/components/Form/index";
import { formSchema } from "./index-option";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { saveCategoryApi, updateCategoryApi } from "/@/api/microresource/novelCategory";
import { useMessage } from "/@/hooks/web/useMessage";

const { createMessage } = useMessage();
const emit = defineEmits(["success"]);
const getTitle = computed(() => (!unref(isUpdate) ? "新增分类" : "编辑分类"));
const isUpdate = ref(true);
const categoryId = ref();
const parentId = ref();

const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { lg: 24, md: 24 },
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  isUpdate.value = !!data?.isUpdate;
  parentId.value = data.parentId || "";
  if (unref(isUpdate)) {
    categoryId.value = data.record?.categoryId;
    parentId.value = data.record?.parentId;
    setFieldsValue({
      ...data.record,
    });
  }
  setModalProps({ confirmLoading: false });
});

async function handleSubmit() {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    let res;
    if (unref(isUpdate)) {
      const param = { ...values, categoryId: categoryId.value, parentId: parentId.value };
      res = await updateCategoryApi(param);
    } else {
      const param = { ...values, categoryId: categoryId.value, parentId: parentId.value };
      res = await saveCategoryApi(param);
    }
    createMessage.success(res.msg);
    closeModal();
    emit("success");
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
